import { exec } from 'child_process';
import { promisify } from 'util';
import os from 'os';
import { ProxyStatusManager } from './proxy-status.js';
import { BackupManager } from './backup-manager.js';

const execAsync = promisify(exec);

/**
 * 重构后的系统代理管理器
 * 采用模块化设计，职责分离
 */
export class SystemProxyManager {
  constructor(proxyHost = 'localhost', proxyPort = 12300) {
    this.platform = os.platform();
    this.proxyHost = proxyHost;
    this.proxyPort = proxyPort;
    this.isProxySet = false;
    
    // 模块化组件
    this.statusManager = new ProxyStatusManager(proxyHost, proxyPort);
    this.backupManager = new BackupManager();
    
    // 超时设置
    this.COMMAND_TIMEOUT = 10000; // 10秒
    this.RESTORE_TIMEOUT = 30000; // 30秒
    
    console.log(`🔧 初始化系统代理管理器: ${this.proxyHost}:${this.proxyPort}`);
  }

  /**
   * 设置系统代理
   */
  async setSystemProxy() {
    try {
      console.log('🔧 正在设置系统代理...');
      
      // 先备份当前设置
      await this.backupManager.backupCurrentSettings();
      
      // 根据平台设置代理
      if (this.platform === 'win32') {
        await this.setWindowsProxy();
      } else if (this.platform === 'darwin') {
        await this.setMacOSProxy();
      } else {
        throw new Error('不支持的操作系统');
      }
      
      this.isProxySet = true;
      console.log(`✅ 系统代理已设置: ${this.proxyHost}:${this.proxyPort}`);
      return true;
      
    } catch (error) {
      console.error('❌ 设置系统代理失败:', error.message);
      // 如果设置失败，立即尝试恢复
      await this.emergencyRestore();
      return false;
    }
  }

  /**
   * 恢复系统代理 - 统一入口
   */
  async restoreSystemProxy() {
    try {
      console.log('🔄 开始恢复系统代理设置...');
      
      // 检查当前状态
      const status = await this.statusManager.getProxyStatus();
      console.log('🔍 当前代理状态:', status);
      
      // 如果当前没有启用代理，直接返回成功
      if (!status.enabled) {
        console.log('✅ 当前系统代理已禁用，无需恢复');
        this.isProxySet = false;
        this.backupManager.cleanupBackupFile();
        return true;
      }
      
      // 如果是我们的代理，进行恢复
      if (status.isOurs) {
        return await this.performRestore();
      } else {
        console.log('⚠️ 当前代理不是我们设置的，跳过恢复');
        return true;
      }
      
    } catch (error) {
      console.error('❌ 恢复系统代理失败:', error.message);
      // 如果恢复失败，执行应急恢复
      return await this.emergencyRestore();
    }
  }

  /**
   * 执行实际的恢复操作
   */
  async performRestore() {
    try {
      // 从文件加载备份
      await this.backupManager.loadBackupFromFile();
      
      const originalSettings = this.backupManager.getOriginalSettings();
      if (originalSettings) {
        console.log('📋 使用备份设置进行恢复');
        
        if (this.platform === 'win32') {
          await this.restoreWindowsProxy(originalSettings);
        } else if (this.platform === 'darwin') {
          await this.restoreMacOSProxy(originalSettings);
        }
        
      } else {
        console.log('⚠️ 没有找到备份设置，强制禁用代理');
        await this.forceDisableProxy();
      }
      
      this.isProxySet = false;
      this.backupManager.cleanupBackupFile();
      console.log('✅ 系统代理设置已恢复');
      return true;
      
    } catch (error) {
      console.error('❌ 执行恢复操作失败:', error.message);
      // 如果恢复失败，强制禁用
      await this.forceDisableProxy();
      return false;
    }
  }

  /**
   * 应急恢复 - 最可靠的恢复方法
   */
  async emergencyRestore() {
    console.log('🚨 执行应急恢复...');
    
    try {
      // 检查当前状态
      const status = await this.statusManager.getProxyStatus();
      
      if (!status.enabled) {
        console.log('✅ 当前系统代理已禁用，无需恢复');
        this.isProxySet = false;
        this.backupManager.cleanupBackupFile();
        return true;
      }
      
      console.log(`📡 当前代理状态: ${status.enabled ? "已启用" : "已禁用"}`);
      if (status.server) {
        console.log(`🌐 代理服务器: ${status.server}`);
        console.log(`🎯 是否为我们的代理: ${status.isOurs ? "是" : "否"}`);
      }
      
      // 尝试正常恢复
      console.log('🔄 尝试正常恢复...');
      const normalRestoreSuccess = await this.performRestore();
      
      if (normalRestoreSuccess) {
        console.log('✅ 正常恢复成功');
        
        // 验证恢复结果
        await this.statusManager.verifyProxyRestore();
        return true;
      }
      
      // 如果正常恢复失败，强制禁用
      console.log('🔄 正常恢复失败，执行强制禁用...');
      await this.forceDisableProxy();
      
      // 验证是否成功
      const success = await this.statusManager.verifyProxyRestore();
      
      if (success) {
        console.log('✅ 应急恢复成功 - 代理已禁用');
        this.isProxySet = false;
        this.backupManager.cleanupBackupFile();
        return true;
      } else {
        console.error('❌ 应急恢复失败 - 代理仍然启用');
        this.printManualRestoreGuide();
        return false;
      }
      
    } catch (error) {
      console.error('❌ 应急恢复失败:', error.message);
      this.printManualRestoreGuide();
      return false;
    }
  }

  /**
   * 设置Windows代理
   */
  async setWindowsProxy() {
    const commands = [
      `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable /t REG_DWORD /d 1 /f`,
      `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyServer /t REG_SZ /d "${this.proxyHost}:${this.proxyPort}" /f`
    ];

    for (const command of commands) {
      await this.executeWithTimeout(command);
    }

    // 刷新代理设置
    await this.refreshWindowsProxy();
  }

  /**
   * 恢复Windows代理
   */
  async restoreWindowsProxy(originalSettings) {
    const commands = [
      `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable /t REG_DWORD /d ${originalSettings.proxyEnable} /f`,
      `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyServer /t REG_SZ /d "${originalSettings.proxyServer}" /f`,
      `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyOverride /t REG_SZ /d "${originalSettings.proxyOverride}" /f`
    ];

    for (const command of commands) {
      await this.executeWithTimeout(command);
    }

    await this.refreshWindowsProxy();
  }

  /**
   * 刷新Windows代理设置
   */
  async refreshWindowsProxy() {
    console.log('🔄 刷新Windows代理设置...');
    
    const refreshCommands = [
      'ipconfig /flushdns',
      'rundll32.exe inetcpl.cpl,ClearMyTracksByProcess 8'
    ];

    for (const command of refreshCommands) {
      try {
        await this.executeWithTimeout(command);
        console.log(`✅ 执行刷新命令成功: ${command}`);
      } catch (error) {
        console.warn(`⚠️ 执行刷新命令失败: ${command} - ${error.message}`);
      }
    }

    // 等待代理设置生效
    console.log('⏳ 等待代理设置生效...');
    await new Promise(resolve => setTimeout(resolve, 2000));
  }

  /**
   * 设置macOS代理
   */
  async setMacOSProxy() {
    // 获取网络服务列表
    const services = await this.statusManager.getMacOSNetworkServices();
    
    for (const service of services) {
      try {
        const commands = [
          `networksetup -setwebproxy "${service}" ${this.proxyHost} ${this.proxyPort}`,
          `networksetup -setsecurewebproxy "${service}" ${this.proxyHost} ${this.proxyPort}`,
          `networksetup -setwebproxystate "${service}" on`,
          `networksetup -setsecurewebproxystate "${service}" on`
        ];

        for (const command of commands) {
          await this.executeWithTimeout(command);
        }

        console.log(`✅ 已为服务 ${service} 设置代理`);
      } catch (error) {
        console.warn(`⚠️ 为服务 ${service} 设置代理失败:`, error.message);
      }
    }
  }

  /**
   * 恢复macOS代理
   */
  async restoreMacOSProxy(originalSettings) {
    if (!originalSettings.services) {
      console.log('⚠️ 没有原始服务设置，禁用所有代理');
      await this.forceDisableProxy();
      return;
    }

    for (const [service, settings] of Object.entries(originalSettings.services)) {
      if (!settings) continue;

      try {
        const { webProxy, httpsProxy } = settings;

        // 恢复HTTP代理
        if (webProxy.enabled) {
          await this.executeWithTimeout(`networksetup -setwebproxy "${service}" ${webProxy.server} ${webProxy.port}`);
          await this.executeWithTimeout(`networksetup -setwebproxystate "${service}" on`);
        } else {
          await this.executeWithTimeout(`networksetup -setwebproxystate "${service}" off`);
        }

        // 恢复HTTPS代理
        if (httpsProxy.enabled) {
          await this.executeWithTimeout(`networksetup -setsecurewebproxy "${service}" ${httpsProxy.server} ${httpsProxy.port}`);
          await this.executeWithTimeout(`networksetup -setsecurewebproxystate "${service}" on`);
        } else {
          await this.executeWithTimeout(`networksetup -setsecurewebproxystate "${service}" off`);
        }

        console.log(`✅ 已恢复服务 ${service} 的代理设置`);
      } catch (error) {
        console.warn(`⚠️ 恢复服务 ${service} 代理失败:`, error.message);
      }
    }
  }

  /**
   * 强制禁用代理
   */
  async forceDisableProxy() {
    console.log('🔄 强制禁用代理...');
    
    try {
      if (this.platform === 'win32') {
        await this.forceDisableWindowsProxy();
      } else if (this.platform === 'darwin') {
        await this.forceDisableMacOSProxy();
      }
      
      console.log('✅ 代理已强制禁用');
      
    } catch (error) {
      console.error('❌ 强制禁用代理失败:', error.message);
      throw error;
    }
  }

  /**
   * 强制禁用Windows代理
   */
  async forceDisableWindowsProxy() {
    const commands = [
      'reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable /t REG_DWORD /d 0 /f',
      'reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyServer /t REG_SZ /d "" /f'
    ];

    for (const command of commands) {
      await this.executeWithTimeout(command);
    }

    await this.refreshWindowsProxy();
  }

  /**
   * 强制禁用macOS代理
   */
  async forceDisableMacOSProxy() {
    const services = await this.statusManager.getMacOSNetworkServices();
    
    for (const service of services) {
      try {
        const commands = [
          `networksetup -setwebproxystate "${service}" off`,
          `networksetup -setsecurewebproxystate "${service}" off`
        ];

        for (const command of commands) {
          await this.executeWithTimeout(command);
        }

        console.log(`✅ 已禁用服务 ${service} 的代理`);
      } catch (error) {
        console.warn(`⚠️ 禁用服务 ${service} 代理失败:`, error.message);
      }
    }
  }

  /**
   * 打印手动恢复指南
   */
  printManualRestoreGuide() {
    console.log('\n' + '='.repeat(60));
    console.log('🔧 手动恢复系统代理设置指南');
    console.log('='.repeat(60));
    
    if (this.platform === 'win32') {
      console.log('Windows用户请执行以下步骤:');
      console.log('1. 打开 设置 → 网络和Internet → 代理');
      console.log('2. 关闭 "使用代理服务器" 选项');
      console.log('3. 或者运行应急恢复脚本: node scripts/emergency-restore.js');
    } else if (this.platform === 'darwin') {
      console.log('macOS用户请执行以下步骤:');
      console.log('1. 打开 系统偏好设置 → 网络');
      console.log('2. 选择当前网络 → 高级 → 代理');
      console.log('3. 取消勾选 "网页代理(HTTP)" 和 "安全网页代理(HTTPS)"');
      console.log('4. 或者运行应急恢复脚本: node scripts/emergency-restore.js');
    }
    
    console.log('='.repeat(60) + '\n');
  }

  /**
   * 获取系统代理管理器状态
   */
  getStatus() {
    const backupStatus = this.backupManager.getBackupStatus();
    
    return {
      isProxySet: this.isProxySet,
      proxyHost: this.proxyHost,
      proxyPort: this.proxyPort,
      platform: this.platform,
      hasBackup: backupStatus.hasBackup,
      backupFileExists: backupStatus.backupFileExists
    };
  }

  /**
   * 执行命令（带超时）
   */
  async executeWithTimeout(command, timeout = this.COMMAND_TIMEOUT) {
    try {
      const { stdout } = await execAsync(command, {
        timeout,
        encoding: 'utf8'
      });
      return stdout.trim();
    } catch (error) {
      throw new Error(`命令执行失败: ${command} - ${error.message}`);
    }
  }
} 